import { getToken } from '@/assets/js/auth'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const request = axios.create({
  baseURL: '',
  timeout: 5000,
  headers: {
    'Content-type': 'application/json'
  }
})

request.interceptors.request.use(function (config) {
  config.headers = config.headers || {}
  config.headers['Authorization'] = `Bearer ${getToken()}`
  // config.headers['Assept-Language'] = window.localStorage.locale
  return config
}, function (error) {
  return Promise.reject(error);
})

request.interceptors.response.use(function (response) {
  const result = response.data
  if (result.code !== 0) {
    ElMessage.error(result.message)
    return result
  }

  return result
}, function (error) {
  return Promise.reject(error.response ? (error.response.data || new Error('Request Error')) : error)
})

export default request